<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="审计任务：" >
                        <Input class="query-form-el"  type="text" v-model="form1.missionName" ></Input>
                    </FormItem>
                </Col>
                <!--<Col span="8">
                    <FormItem label="组长姓名：" >
                        <Input class="query-form-el"  type="text" v-model="form1.groupLeaderName" ></Input>
                    </FormItem>
                </Col>
                
                <Col span="8">
                    <FormItem label="审计单位："  >
                        <Select class="query-form-el" filterable v-model="form1.locationId"  >
                            <Option v-for="item in locationList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                        </Select>
                    </FormItem>
                </Col>-->
                <Col span="8">
                    <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                    <Button   class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
        </Form>

        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows'
               :loading="buttonLoading" size="small" border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
       
        <Modal title="指派整改" v-model="model2" :width=800 >
                    <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom"  :label-width="160" >
                        <Row type="flex" justify="space-around">
                            <Col span="23" >
                                <FormItem label="审计任务：" prop="stdOrgName">
                                    {{form1datacopy.missionName}}
                                </FormItem>
                            </Col>

                            <!--
                            <Col span="11" >
                                <FormItem label="审计类型：" prop="location" >
                                    {{form1datacopy.auditTypeName}}
                                </FormItem>
                            </Col>-->
                        </Row>

                        <Row type="flex" justify="space-around">
                            <Col span="23" >
                                <FormItem label="审计单位：" prop="stdOrgName">
                                    {{form1datacopy.auditedOrgName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around">
                            <Col span="11" >
                                <FormItem label="组长：" prop="location" >
                                    {{form1datacopy.groupLeaderName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="创建人：" prop="createUserId" >
                                    {{form1datacopy.createUserName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around">
                            <Col span="11" >
                                <FormItem label="开始时间：" >
                                    {{formatDate(new Date(form1datacopy.planStart), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="结束时间：">
                                    {{formatDate(new Date(form1datacopy.planEnd), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="整改人：" prop="rectLeaderId">
                                    <Select class="query-form-el"  v-model="form1datacopy.rectLeaderId" label-in-value @on-change='rectLeaderChange' >
                                        <Option v-for="item in auditHandlers" :value="item.adtHandlerId" :key="item.adtHandlerId">{{ item.adtHandlerName }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="整改时间：" prop="rectTime" >
                                    <DatePicker type="date"  class="query-form-el"  v-model="form1datacopy.rectTime"   format="yyyy-MM-dd"  placeholder="请选择"></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="整改要求：">
                                    <Input v-model="form1datacopy.rectDesc" type="textarea" :rows="3" />
                                </FormItem>
                            </Col>
                        </Row>
                      <!--  <Row type="flex" justify="center" class="code-row-bg">
                            <Col span="23" >
                                <FormItem>
                                    <Button class='ivu-btn-save' @click="submit('form1datacopy')" >确定</Button>
                                    <Button class='ivu-btn-cancel' @click="onCancel" >取消</Button>
                                </FormItem>
                            </Col>
                        </Row>-->
                    </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="submit('form1datacopy')" >确定</Button>
                <Button class='ivu-btn-cancel' @click="onCancel" >取消</Button>
            </div>
        </Modal>

        <Modal title="问题清单" :transfer=false footer-hide v-model="expertSelectModal"  :width=1300 >
            <selectProblems  ref="selExpert" @getActivityData="getActivityData" @closeModal1="closeModal1"  >
            </selectProblems>
        </Modal>

    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js' 
    import {sessionStorage} from '@/common/cacheUtils.js';
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import selectProblems from "./selectProblems.vue"
    import { getAditStatsName } from './auditUtils' 

    export default {
        components:{
            cascaderDom,selectProblems
        },
        data(){
            return{
                auditHandlers: [],
                auditTypes:[
                    {id:'1',name:"集团审核"},
                    {id:'2',name:"二级集团审核"},
                    {id:'3',name:"自评价"}
                    ],
                expertSelectModal:false,
                upLoadList:[],
                appStatusList:[],
                locationList:[],
                stdRankList:[],
                downloadUrl:Api.downloadMongoFile,
                upUrl:Api.uploadMongoFile,
                switchFlag : false,
                form1: {
                },
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                dataTable:[],
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                     {
                        title: '审计任务',
                        minWidth: 250,
                        align: 'center',
                        key:'missionName',
                    },
                    //  {
                    //     title: '审计类型',
                    //     minWidth: 150,
                    //     align: 'center',
                    //     key:'auditTypeName',
                    // },
                    {
                        title: '审计单位',
                        minWidth: 250,
                        align: 'center',
                        key:'auditedOrgName',
                    },
                    // {
                    //     title: '审计状态',
                    //     minWidth: 150,
                    //     align: 'center',
                    //     render: (h, params) => {
                    //         return h('span', getAditStatsName(params.row.auditState))
                    //     }
                    // },
                    {
                        title: '整改人',
                        minWidth: 130,
                        align: 'center',
                        key:'rectLeader',
                    },
                    // {
                    //     title: '整改要求',
                    //     minWidth: 250,
                    //     align: 'center',
                    //     key:'rectDesc',
                    // },
                    
                    // {
                    //     title: '整改时间',
                    //     minWidth: 150,
                    //     align: 'center',
                    //     key:'rectTime',
                    //     render:(h,params)=>{
                    //         return h('div',[
                    //             (this.formatDate(new Date(params.row.rectTime), 'yyyy-MM-dd'))
                    //         ]);
                    //     }
                    // },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 200,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params,1);
                                        }
                                    }
                                }, '问题清单'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.auditState === '0'  ? '' : '#d0d0d0' ,
                                        pointerEvents: params.row.auditState === '0'  ? '':'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params,2);
                                        }
                                    }
                                }, '指派整改'),
                            ]);
                        }
                    },

                ],
                ruleCustom : {
                    rectLeaderId: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],
                    auditedOrgId: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],
                    rectDesc: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],
                    stdRankId: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],
                    groupLeaderName: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],
                    cover: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],

                    planEnd: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    planStart: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],

                },
                auditedOrgName:'',
                auditedOrgId:'',
                add:false,
                model1:false,
                model2:false,
                showdata: {},
                location:null,
                form1datacopy:{

                },
                files :[],
                buttonLoading:false,tableHeight:10,
            }
        },
        mounted() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.selectCodingSort();
            this.query();
        },
        methods:{
            rectLeaderChange(appStatus) {
                if(appStatus){
                    this.form1datacopy.rectLeaderId = appStatus.value;
                    this.form1datacopy.rectLeader = appStatus.label;
                }
            },
           
            auditTypesChange(stdRank){
                if(stdRank){
                    this.form1datacopy.auditTypeId = stdRank.value;
                    this.form1datacopy.auditTypeName = stdRank.label;
                }
            },
            onCancel() {
                this.model2 = false
            },
            closeModal1(){
                this.expertSelectModal = false;
            },
            getActivityData(row){

                if(this.$refs.selExpert.isLeader == 1){
                    this.form1datacopy.groupLeaderId = row.expertId;
                    this.form1datacopy.groupLeaderName = row.userName;
                    this.expertSelectModal = false;
                }else{
                    this.form1datacopy.membersId = row.$membersId
                    this.form1datacopy.membersName = row.$membersName
                }
            },
           
            selectLocation(location){
                this.form1datacopy.locationId = location.value;
                this.form1datacopy.location = location.label;
            },
            selectstdRank(stdRank){
                this.form1datacopy.stdRankId = stdRank.value;
                this.form1datacopy.stdRank = stdRank.label;
            },
            selectAppStatus(appStatus){
                this.form1datacopy.appStatusId = appStatus.value;
                this.form1datacopy.appStatus = appStatus.label;
            },
            beforeUploadOther(file) {
                this.files.push(file);

                return false;
            },
            deleteFile(index){
                this.files.splice(index,1);
            },
            setOrgId(data) {
                this.form1datacopy.auditedOrgId = data[data.length - 1];
            },
            setOrgName(data) {
                this.form1datacopy.auditedOrgName = data;
            },
            deleteData(params) {
                let url = Api.deleteAdtMission;
                this.$http.get(url,  {params: {id :  params.row.missionId}}).then((res) => {
                    if (res.status === 200) {
                        this.$Message.success('成功');
                        this.query()
                    }else if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);

                    }
                }).catch(e => {
                    this.$Message.error('请求失败' + e);
                })
            },


            getSelectRows (rows){
                this.deleteRows = rows;
            },
            
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            selectCodingSort(){
                this.$http.get(Api.queryCodeDetailBySortId + '/AS-000001', {params: {}}).then((res) => {
                    this.appStatusList = res.data.data;
                });
                this.$http.get(Api.queryCodeDetailBySortId + '/REGION-000001', {params: {}}).then((res) => {
                    this.locationList = res.data.data;
                });
                this.$http.get(Api.queryCodeDetailBySortId + '/SSL-000001', {params: {}}).then((res) => {
                    this.stdRankList = res.data.data;
                });

            },
            switchQuery(flag){
                this.switchFlag = flag;
                if(!this.switchFlag){
                    this.tableHeight = window.innerHeight - 220;
                }else{
                    this.tableHeight = window.innerHeight - 315;
                }
            },
            reset() {
                this.form1 = {};
                this.query();
            },
            query() {this.buttonLoading=true
                let userId = sessionStorage('userId').getObject('userId').userId;
                let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    orgId:orgId,
                    createUserId: userId
                };
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
                data.groupLeaderName = this.form1.groupLeaderName || ''
                let url = Api.queryAdtMissionAssign;
                this.$http.get(url, {params: data}).then((res) => {

                    this.dataTable = res.data.data;
                    this.pagedata.total = res.data.data.totalSize;this.buttonLoading=false
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            showData(data, flag) {
                this.auditedOrgId  = data.row.auditedOrgId;
                this.auditedOrgName = data.row.auditedOrgName;
                if (flag == 1) {
                    this.showdata = data.row;
                    this.$refs.selExpert.missionId = data.row.missionId
                    this.$refs.selExpert.query()
                    this.expertSelectModal = true;
                 } else {

                    this.auditHandlers = []
                    let orgId = data.row.auditedOrgId
                    this.$http.get(Api.getAuditHandlers, {params: {orgId}}).then((res) => {
                        this.auditHandlers = res.data.data;
                        //console.log(1111,this.auditHandlers)
                    });


                     //check mission's problems
                    // console.log(1111,data.row)
                    this.$http.get(Api.queryAdtProblemsByMissionId, {params: {missionId:data.row.missionId}}).then((res) => {
                        console.log(345,res.data.type)

                        if(res.data.type=='1' || res.data.type=='2'){
                            let message ="" 
                            this.$Modal.confirm({
                                title: '',
                                content: '<p>存在未确认审计问题</p>',
                                okText: '确认',
                                onOk: () => {
                                
                                },
                                cancelText: '取消'
                            });
                        }else{
                            this.form1datacopy = JSON.parse(JSON.stringify(data.row));
                            this.form1datacopy.rectTime = new Date()
                            this.form1datacopy.planTaskId=this.form1datacopy.missionId
                            this.form1datacopy.rectLeaderId = '';
                            this.form1datacopy.rectLeader = '';
                            this.add = true;
                            this.model2 = true;
                        }
                    });

                }
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            submit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let userId = sessionStorage('userId').getObject('userId').userId;
                        let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                        this.form1datacopy.createUsrId = userId;
                        this.form1datacopy.createOrgId = orgId;

                        this.$Modal.confirm({
                            title: '指派整改确认',
                            content: '<p>此操作无法撤销，请确认指派整改信息正确。</p>',
                            okText: '确认',
                            onOk: () => {
                                this.$http.post(Api.createAdtProblemRect, this.form1datacopy).then((res) => {
                                    if (res.status === 200) {
                                        this.$Message.success('成功');
                                        this.model2 = false;
                                        this.query()
                                    }else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                        this.model2 = false;
                                    }
                                }).catch(e => {
                                    this.model2 = false;
                                    this.query();
                                    this.$Message.error("数据获取失败")
                                })
                            },
                            cancelText: '取消'
                        });
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },

        },
        watch:{
            "model1":function(qw,er){
                if(qw && this.model1){
                    setTimeout(()=>{
                        this.$refs.trainOrg.setCurrentOrg();

                    },100)
                }else{
                    this.$refs.trainOrg.setCurrentOrg();

                }
            },

        },


    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
</style>
